package glpm

import (
	"context"
	"fmt"
	"strings"
)

// DpkgManager DPKG包管理器实现
type DpkgManager struct {
	*BaseManager
}

// NewDpkgManager 创建DPKG包管理器
func NewDpkgManager(config *ManagerConfig) *DpkgManager {
	base := NewBaseManager("dpkg", config)
	return &DpkgManager{
		BaseManager: base,
	}
}

// Install 安装包
func (dm *DpkgManager) Install(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要安装的包文件路径")
	}
	
	args := []string{"-i"}
	args = append(args, packages...)
	
	_, err := dm.executeCommand(ctx, args...)
	return err
}

// Remove 移除包
func (dm *DpkgManager) Remove(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要移除的包名")
	}
	
	args := []string{"-r"}
	args = append(args, packages...)
	
	_, err := dm.executeCommand(ctx, args...)
	return err
}

// Update 更新包列表（DPKG不支持更新操作）
func (dm *DpkgManager) Update(ctx context.Context) error {
	return fmt.Errorf("DPKG包管理器不支持更新操作")
}

// Upgrade 升级包（DPKG不支持升级操作）
func (dm *DpkgManager) Upgrade(ctx context.Context, packages []string) error {
	return fmt.Errorf("DPKG包管理器不支持升级操作")
}

// Search 搜索包
func (dm *DpkgManager) Search(ctx context.Context, pattern string) ([]PackageInfo, error) {
	output, err := dm.executeCommand(ctx, "-l", pattern)
	if err != nil {
		return nil, err
	}
	
	return dm.parseSearchOutput(output)
}

// Info 获取包信息
func (dm *DpkgManager) Info(ctx context.Context, packageName string) (*PackageInfo, error) {
	output, err := dm.executeCommand(ctx, "-s", packageName)
	if err != nil {
		return nil, err
	}
	
	return dm.parseInfoOutput(output)
}

// ListInstalled 列出已安装的包
func (dm *DpkgManager) ListInstalled(ctx context.Context) ([]PackageInfo, error) {
	output, err := dm.executeCommand(ctx, "-l")
	if err != nil {
		return nil, err
	}
	
	return dm.parseListOutput(output)
}

// IsInstalled 检查指定包是否已安装
func (dm *DpkgManager) IsInstalled(ctx context.Context, packageName string) (bool, error) {
	output, err := dm.executeCommand(ctx, "-s", packageName)
	if err != nil {
		return false, err
	}
	
	// 检查输出中是否包含 "Status: install ok installed"
	if strings.Contains(output, "Status: install ok installed") {
		return true, nil
	}
	
	return false, nil
}

// parseSearchOutput 解析搜索输出
func (dm *DpkgManager) parseSearchOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "Desired=") || strings.HasPrefix(line, "||/") {
			continue
		}
		
		// 解析格式: ii  package  version  architecture  description
		parts := strings.Fields(line)
		if len(parts) >= 4 {
			status := parts[0]
			pkgName := parts[1]
			version := parts[2]
			arch := parts[3]
			description := ""
			
			if len(parts) > 4 {
				description = strings.Join(parts[4:], " ")
			}
			
			packages = append(packages, PackageInfo{
				Name:         pkgName,
				Version:      version,
				Architecture: arch,
				Description:  description,
				Status:       status,
			})
		}
	}
	
	return packages, nil
}

// parseInfoOutput 解析包信息输出
func (dm *DpkgManager) parseInfoOutput(output string) (*PackageInfo, error) {
	info := &PackageInfo{}
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		
		if strings.HasPrefix(line, "Package:") {
			info.Name = strings.TrimSpace(strings.TrimPrefix(line, "Package:"))
		} else if strings.HasPrefix(line, "Version:") {
			info.Version = strings.TrimSpace(strings.TrimPrefix(line, "Version:"))
		} else if strings.HasPrefix(line, "Architecture:") {
			info.Architecture = strings.TrimSpace(strings.TrimPrefix(line, "Architecture:"))
		} else if strings.HasPrefix(line, "Description:") {
			info.Description = strings.TrimSpace(strings.TrimPrefix(line, "Description:"))
		} else if strings.HasPrefix(line, "Status:") {
			info.Status = strings.TrimSpace(strings.TrimPrefix(line, "Status:"))
		}
	}
	
	return info, nil
}

// parseListOutput 解析列表输出
func (dm *DpkgManager) parseListOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "Desired=") || strings.HasPrefix(line, "||/") {
			continue
		}
		
		// 解析格式: ii  package  version  architecture  description
		parts := strings.Fields(line)
		if len(parts) >= 4 {
			status := parts[0]
			if status == "ii" {
				pkgName := parts[1]
				version := parts[2]
				arch := parts[3]
				description := ""
				
				if len(parts) > 4 {
					description = strings.Join(parts[4:], " ")
				}
				
				packages = append(packages, PackageInfo{
					Name:         pkgName,
					Version:      version,
					Architecture: arch,
					Description:  description,
					Status:       "installed",
				})
			}
		}
	}
	
	return packages, nil
}